﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MovieRental.XmlDataProviderCore;
using System.Configuration;
using MovieRental.GeneralDataExceptions;
using MovieRental.DataInterfaces;

namespace MovieRental.XmlRepositoryLibrary
{
    public abstract class XmlRepository<TEntity>
    {
        private XmlDataProvider _provider;

        public XmlRepository(XmlDataProvider provider)
        {
            _provider = provider;
        }

        protected XmlDataContext CreateContext()
        {
            return _provider.CreateContext();
        }

        public void Save(TEntity entity)
        {
            if (entity == null)
                throw new ArgumentNullException();
            using (var context = CreateContext())
            {
                try
                {
                    context.Save(entity);
                }
                catch (Exception ex)
                {
                    throw new DbException("Can't save object in the database", ex);
                }
            }
        }

        public void Delete(TEntity entity)
        {
            using (var context = CreateContext())
            {
                try
                {
                    context.Delete(entity);
                }
                catch (Exception ex)
                {
                    throw new ItemNotFoundException(entity.ToString(), ex);
                }
            }
        }

        public IEnumerable<TEntity> LoadAll()
        {
            using (var context = CreateContext())
            {
                return context.GetAllForType(typeof(TEntity)).Select(x => (TEntity)x);
            }
        }
    }
}
